import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/JhPickerTool.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/putaway/putawaydialogscreen.dart';
import 'package:opene/ui/putaway/putawaymodel.dart';
import 'package:opene/ui/returns/finalprocess/finalprocessrpsreen.dart';
import 'package:opene/ui/returns/preprocess/preprocessreasonscreen.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:toast/toast.dart';

class PreprocessTrkScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return PreprocessTrkScreenPage();
  }
}

class PreprocessTrkScreenPage extends StatefulWidget {

  @override
  _PreprocessTrkPageState createState() => _PreprocessTrkPageState();
}

class _PreprocessTrkPageState extends BaseState<PreprocessTrkScreen> {

  final TextEditingController skuEditingController = TextEditingController();
  final TextEditingController qtyEditingController = TextEditingController();
  FocusNode textFiledNode = FocusNode();
  FocusNode skuFocusNode = FocusNode();
  FocusNode qtyFocusNode = FocusNode();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Returns: Tracking";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    textFiledNode.dispose(); // 不要忘记销毁FocusNode
    skuFocusNode.dispose(); // 不要忘记销毁FocusNode
    qtyFocusNode.dispose(); // 不要忘记销毁FocusNode
    super.dispose();
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    focusNode: textFiledNode,
                    controller: textEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                      preProcessCheckTrk(text, false);
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            if (text == null) {
                              return;
                            }
                            setState(() {
                              textEditingController.text = text;
                            });
                            print(text); //拿到扫描结果
                            preProcessCheckTrk(text, false);
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: "scan tracking number",
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                    onChanged: (text) {
                      code = text;
                    },
                  ),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    focusNode: skuFocusNode,
                    controller: skuEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                      productGet(text, false);
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            print(text); //拿到扫描结
                            if(Utils.isEmpty(text)){
                              return;
                            }
                            productGet(text, false);
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: "scan sku/barcode",
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),

                  ),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "*",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.red, fontSize: 14.0),
              ),
              Text(
                "QTY: ",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    focusNode: qtyFocusNode,
                    keyboardType: TextInputType.number,
                    controller: qtyEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                    },
                  ),
                ),
              ),
              SizedBox(
                width: 5,
              ),
              GestureDetector(
                onTap: () {
                  if (Utils.isEmpty(qtyEditingController.text)) {
                    return;
                  }
                  if (!Utils.isInteger(qtyEditingController.text)) {
                    return;
                  }
                  int qty = int.parse(qtyEditingController.text);
                  if (qty < 1) {
                    qtyEditingController.text = "0";
                    return;
                  }
                  qty--;
                  qtyEditingController.text = "${qty}";
                },
                child: Icon(
                  Icons.remove_circle_outline,
                  size: 35,
                  color: MyAppTheme.nearlyBlue,
                ),
              )
            ],
          ),
          SizedBox(
            height: 5,
          ),
        ],
      ),
    );
  }


  void preProcessCheckTrk(String id, bool isNext) async {
    setState(() {
      updateHint('');
      skuEditingController.text = "";
      qtyEditingController.text = "0";
    });

    Map<String, dynamic> map = new HashMap();
    map["id"] = id;

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.preProcessCheckTrk, params: map);

    if (baseResponse.status == 200) {
      skuFocusNode.requestFocus();
      if (isNext) {
        setSubmit();
      }
    } else if (baseResponse.status == 8013) {
      skuFocusNode.requestFocus();
      if (isNext) {
        showDialog(
          context: context,
          builder: (context) => NewPreprocessDialog(processType:baseResponse.msg),
        ).then((value) =>
        {
          if ((value != null) && value )
            {
              setSubmit()
            }
        });
      }
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }


  String sku;
  void productGet(String barcode, bool isSubmit) async {
    updateHint('');
    sku = null;
    Map<String, dynamic> map = new HashMap();
    map["barcode"] = barcode;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.product, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      sku = barcode;
      qtyFocusNode.requestFocus();
    }else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }


  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    setSubmit();
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
      skuEditingController.text = "";
      qtyEditingController.text = "0";
      textFiledNode.requestFocus();
    });
  }

  void setSubmit() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("Please input  trk#", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (Utils.isEmpty(skuEditingController.text)) {
      ToastContext().init(context);
      Toast.show("Please input sku/barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (Utils.isEmpty(qtyEditingController.text)) {
      ToastContext().init(context);
      Toast.show("Please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if(!Utils.isInteger(qtyEditingController.text)){
      ToastContext().init(context);
      Toast.show("Please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    int qty = int.parse(qtyEditingController.text);

    PreprocessReasonQr bounceReasonQr = new PreprocessReasonQr();
    bounceReasonQr.tracking_number=textEditingController.text;
    bounceReasonQr.sku_barcode=(textEditingController.text);
    bounceReasonQr.quantity=(qty);
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => PreprocessReasonScreen(bounceReasonQr: bounceReasonQr)),
    ).then((value) {

    }).catchError((error) {
      // 错误处理
      print("An error occurred: $error");
    });
  }

}
